package com.jyw.business.ast.controller;

import brave.http.HttpServerResponse;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.jyw.business.ast.domain.AstInfo;
import com.jyw.business.ast.domain.dto.AstOptionDto;
import com.jyw.business.ast.domain.dto.web.*;
import com.jyw.business.ast.domain.vo.web.AstDetailVo;
import com.jyw.business.ast.domain.vo.web.AstInfoExportVo;
import com.jyw.business.ast.domain.vo.web.AstPageVo;
import com.jyw.business.ast.domain.vo.web.AstPrintVo;
import com.jyw.business.ast.service.IAstInfoService;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.page.BasePage;
import com.jyw.common.core.page.TableDataInfo;
import com.jyw.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;

/**
 * @author 沈峻
 * @ClassName AstSignController
 * @Description 资产登记
 * @Date 2023/9/20 10:21
 **/
@RestController
@RequestMapping("ast/sign")
@Api(tags = "资产登记")
public class AstSignController extends BaseController {
    /**
     * 资产信息接口
     */
    @Resource
    private IAstInfoService infoService;


    @PostMapping("add")
    @PreAuthorize("@ss.hasPermi('asset:sign:add')")
    @ApiOperation("单个登记")
    public CommonResult add(@RequestBody AstAddDto addDto) {
        infoService.add(addDto);
        return CommonResult.success();
    }

    @PostMapping("batchAdd")
    @PreAuthorize("@ss.hasPermi('asset:sign:batch')")
    @ApiOperation("批量登记")
    public CommonResult batchAdd(@RequestBody AstBatchAddDto addDto) {
        infoService.batchAdd(addDto);
        return CommonResult.success();
    }

    @PostMapping("edit")
    @PreAuthorize("@ss.hasPermi('asset:sign:edit')")
    @ApiOperation("资产编辑")
    public CommonResult edit(@RequestBody @Valid AstEditDto editDto) {
        infoService.edit(editDto);
        return CommonResult.success();
    }

    @GetMapping("list")
    @PreAuthorize("@ss.hasPermi('asset:sign:page')")
    @ApiOperation("分页查询")
    public TableDataInfo<AstPageVo> page(BasePage page, AstPageDto dto) {
        return getDataTable(infoService.signPage(page, dto));
    }

    @GetMapping("export")
    @PreAuthorize("@ss.hasPermi('asset:sign:export')")
    @ApiOperation("导出")
    public void export(HttpServletResponse response,AstPageDto dto) throws UnsupportedEncodingException {

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("资产台账", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<AstInfoExportVo> list = infoService.export(dto);
        // 创建 ByteArrayOutputStream 实例
        try {
            EasyExcel
                    .write(response.getOutputStream())
                    .withTemplate(new ClassPathResource("template/assets_export.xlsx").getInputStream())
                    .sheet()
                    .doFill(list);
        } catch (IOException e) {
            throw new ServiceException("导出失败");
        }
    }

    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasAnyPermi('asset:sign:detail,asset:sign:edit')")
    @ApiOperation("详情查询")
    public CommonResult<AstDetailVo> info(@PathVariable("id") Long id) {
        return CommonResult.success(infoService.detail(id));
    }


    /**
     * 删除资产
     */
    @PreAuthorize("@ss.hasPermi('asset:sign:remove')")
    @DeleteMapping("/{ids}")
    @ApiOperation("删除资产")
    public CommonResult remove(@PathVariable Long[] ids) {
        infoService.remove(ids);
        return CommonResult.success();
    }

    @PutMapping("dispose")
    @PreAuthorize("@ss.hasPermi('asset:sign:dispose')")
    @ApiOperation("到期处置")
    public CommonResult dispose(@RequestBody @Valid AstExpireDisposeDto dto) {
        infoService.dispose(dto);
        return CommonResult.success();
    }

    /**
     * 下载资产模板
     */
    @GetMapping("template")
    @ApiOperation("下载资产模板")
    @PreAuthorize("@ss.hasPermi('ast:sign:import')")
    public void template(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("资产模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        IOUtils.copy(new ClassPathResource("template/assets_import.xlsx").getInputStream(),response.getOutputStream());
        response.flushBuffer();
    }

    /**
     * 下载耗材模板
     */
    @PostMapping("import")
    @ApiOperation("资产导入")
    @PreAuthorize("@ss.hasPermi('ast:sign:import')")
    public CommonResult importTemplate(@RequestParam("file") MultipartFile file) {
        infoService.importData(file);
        return CommonResult.success();
    }

    @GetMapping("option")
    @ApiOperation("可选资产")
    public CommonResult<List<AstPageVo>> option(AstOptionDto dto) {
        List<AstPageVo> list = infoService.option(dto);
        return CommonResult.success(list);
    }

    @GetMapping("print")
    @ApiOperation("资产打印")
    @ApiImplicitParam(value = "ids",name = "资产id集合(1,2,3)",required = true)
    public CommonResult<List<AstPrintVo>> print(Long[] ids){
        List<AstPrintVo> print = infoService.print(ids);
        return CommonResult.success(print);
    }

}
